package com.first.wchat;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import com.first.wchat.BroadcastActivity.Hodler;
import com.first.wchat.ChatActivity.MyOnClickListener;
import com.first.wchat.data.DeviceAndGroupListener;
import com.first.wchat.data.MSGDataManager;
import com.first.wchat.data.MSGDataManager.ImageMessageData;
import com.first.wchat.data.MSGDataManager.MessageData;
import com.first.wchat.widget.DeviceAdapter;
import com.wchat.network.Controller;
import com.wchat.network.device.BroadCastTarget;
import com.wchat.network.device.Device;
import com.wchat.network.device.Group;
import com.wchat.network.device.GroupParam;
import com.wchat.network.device.SendTarget;
import com.wchat.util.Util;

//import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class GroupActivity extends Activity implements DeviceAndGroupListener{
	
	private final static int MAXGROUP = 10;
	Gallery  mGroups;
	ListView mGroupMembers;
	ListView mMessages;
	EditText mInput;
	Button   mSend;
	Button   mFindImage;
	Button   mSwitcher;
	TextView mGroupName;
	LinearLayout   mContentLayout;
	LinearLayout   mMemberLayout;
	LinearLayout   mMessageLayout;
	Uri mUri;
	int mGroupIndex;
	Dialog mCheckDailog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.group);
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		initGroup();
		MSGDataManager.getInstance().addListener(this);
	}
	
	protected void onStart()
	{
		super.onStart();
	}
	
	
	protected void onDestroy()
	{
		
		MSGDataManager.getInstance().removeListener(this);
		super.onDestroy();

	}
	
	protected void onActivityResult (int requestCode, int resultCode, Intent data) 
    {
    	
    	if(requestCode == 1 && resultCode == Activity.RESULT_OK && data!= null)
    	{
    		mUri = data.getData();
    		mInput.setText(mUri.toString());
    	}
    }
	
	public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.clear();
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.group_menu, menu);
		return super.onCreateOptionsMenu(menu);
    	
    }
    public boolean onOptionsItemSelected(MenuItem item){
    	
    	if(item.getItemId() == R.id.createGroup)
    	{
    		if(mGroups.getCount()>= MAXGROUP)
    			Toast.makeText(this, "User can create group no more than ten!", Toast.LENGTH_SHORT).show();
    		else
    			showAddGroupDialog();
    	}
    	
    	return true;
    }
    
	
	private void initGroup()
	{
		mGroups = (Gallery)findViewById(R.id.group_list);
		mGroups.setAdapter(new GroupAdapter(MSGDataManager.getInstance().getGroups()));
		mGroups.setOnItemLongClickListener(new MyGroupOnItemLongClickListener());
		mGroups.setOnItemSelectedListener(new MyGroupOnSelectedListener());
		mGroups.setSelection(mGroupIndex);
		mSwitcher =  (Button)findViewById(R.id.group_switcher);
		mSwitcher.setOnClickListener(new MyOnClickListener());
		mContentLayout =(LinearLayout)findViewById(R.id.group_memberLayout);
		initGroupMember((Group)mGroups.getSelectedItem());
	}
	
	private void initGroupMember(Group g)
	{
		if(g == null)
			return;
		
		mMemberLayout = (LinearLayout)findViewById(R.id.groupMemberlayout);
		mMessageLayout = (LinearLayout)findViewById(R.id.Msglayout);
		mGroupName = (TextView)findViewById(R.id.group_name);
		mGroupName.setText("Current Group :"+g.getParam().name);
		mGroupMembers = (ListView)findViewById(R.id.groupMember_list);
		mMessages = (ListView)findViewById(R.id.groupMessage_list);
		
		final Group group =g;
		if(!isInGroup(group,Controller.getInstance().getLocalDevice()))
		{
			
			mGroupMembers.setAdapter(null);
			mMessages.setAdapter(null);
			
			if(mCheckDailog == null || !mCheckDailog.isShowing())
			{
				mCheckDailog =new AlertDialog
		    		.Builder(GroupActivity.this)
					.setIcon(android.R.attr.alertDialogStyle)
					.setTitle("Error")
		    		.setMessage("you aren't the member of this group!")
		    		.setPositiveButton("ok", null)
		    		.create();
					mCheckDailog.show();
			}
			
			return ;
			
		}
			
		DeviceAdapter device = new DeviceAdapter(getApplicationContext(),MSGDataManager.getInstance().getDevices(g));
		mGroupMembers.setAdapter(device);
		MsgAdapter message = new MsgAdapter(MSGDataManager.getInstance().getMessage(g));
		mMessages.setAdapter(message);
		
		mInput = (EditText)findViewById(R.id.inputTool);
		mSend = (Button)findViewById(R.id.send);
		mSend.setOnClickListener(new MyOnClickListener());
		
		mFindImage =(Button)findViewById(R.id.findImage);
		mFindImage.setOnClickListener(new MyOnClickListener());
	}
	
	private void updateMessage(MessageData md)
	{

		if(mMessages ==null)
			return;
		MsgAdapter adapter = (MsgAdapter)mMessages.getAdapter();
		adapter.add(md);
		adapter.notifyDataSetChanged();
	}
	
	private void showAddGroupDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		View view = View.inflate(this, R.layout.create_group, null);
		final TextView label = (TextView) view.findViewById(R.id.input_title);
		label.setText("input group name: ");
		final EditText namEditText = (EditText) view.findViewById(R.id.input_group_name);
		final EditText pwEditText = (EditText) view.findViewById(R.id.input_pw);
		builder.setView(view);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String text = namEditText.getEditableText().toString();
				GroupParam param = new GroupParam();
				param.name = text;
				param.password = pwEditText.getEditableText().toString();
				MainActivity.getUserAction().createGroup(param);
				updateGroup();
			}
		});
		builder.setNegativeButton("Cancel", null);
		builder.show();
	}
	private void updateGroup()
	{
		initGroup();
	}
	
	
	private void send()
	{
		SendTarget target = (Group)mGroups.getSelectedItem();
		String msg = mInput.getEditableText().toString();
		if(mUri == null)
		{
			if(msg == null || msg== "")
			{
				Toast.makeText(GroupActivity.this, "can't send since no message!", Toast.LENGTH_SHORT).show();
				return;
			}
			MSGDataManager.getInstance().addMessage(target, Controller.getInstance().getDeviceContext().getLocal(),msg,null);
			MainActivity.getUserAction().sendText(msg, target);
		}
		else
		{
			String path = Util.getUriFilePath(GroupActivity.this, mUri);
			File imageFile = new File(path);
			MSGDataManager.getInstance().addMessage(target, Controller.getInstance().getDeviceContext().getLocal(),Util.getScaleBitmap(imageFile),imageFile.getAbsolutePath());
			MainActivity.getUserAction().sendImage(imageFile, target);
			mUri = null;
		}
		mInput.clearComposingText();
		mInput.setText("");

	}
	
	private void switchModule()
	{
		if(mMemberLayout==null || mMessageLayout ==null)
			return;
		
		if(mMemberLayout.getVisibility() == View.GONE)
		{
			
			RotateAnimation myAnimation=new RotateAnimation(-90.0f, 0.0f,

					 Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
			myAnimation.setDuration(500);
			
			mContentLayout.startAnimation(myAnimation);
	        
	        mMessageLayout.setVisibility(View.GONE);
			mMemberLayout.setVisibility(View.VISIBLE);
	        initGroupMember((Group)mGroups.getSelectedItem());
		}
		else
		{

			RotateAnimation myAnimation=new RotateAnimation(90.0f, 0.0f,

					 Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
			myAnimation.setDuration(500);
			mContentLayout.startAnimation(myAnimation);
			
	        mMemberLayout.setVisibility(View.GONE);
			mMessageLayout.setVisibility(View.VISIBLE);
		}
		
	}
	
	private boolean isInGroup(Group g,Device d)
	{
		ArrayList<Device> devices = Controller.getInstance().getDeviceContext().getDevicesInGroup(g.getGroupid());
		
		if(devices == null || devices.size() == 0)
			return false;
		
		if(devices.contains(d))
			return true;
		
		return false;
	}
	
	class MyGroupOnSelectedListener implements OnItemSelectedListener
	{

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			mGroupIndex = position;
			
			initGroupMember((Group)mGroups.getItemAtPosition(position));
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}
	class MyGroupOnItemLongClickListener implements OnItemLongClickListener
	{

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			
			final Group group =((Group)arg0.getItemAtPosition(position));
			AlertDialog.Builder builder = new AlertDialog.Builder(GroupActivity.this);
			View view = View.inflate(GroupActivity.this, R.layout.promote_name, null);
			final TextView label = (TextView) view.findViewById(R.id.input_label);
			label.setText("Join Group:"+group.getParam().name);
			final EditText namEditText = (EditText) view.findViewById(R.id.input_name);
			namEditText.setHint("Pass word");
			builder.setView(view);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					
					if(isInGroup(group,Controller.getInstance().getLocalDevice()))
					{
						new AlertDialog
			    		.Builder(GroupActivity.this)
						.setIcon(android.R.attr.alertDialogStyle)
						.setTitle("Error")
			    		.setMessage("you have been in this group!")
			    		.setPositiveButton("ok", null)
			    		.create().show();
						return ;
					}
					
					if(group.getParam().password!= null && group.getParam().password!="")
					{
						if(!group.getParam().password.equals(namEditText.getEditableText().toString()))
						{
							new AlertDialog
				    		.Builder(GroupActivity.this)
							.setIcon(android.R.attr.alertDialogStyle)
							.setTitle("Error")
				    		.setMessage("Wrong pass word!")
				    		.setPositiveButton("ok", null)
				    		.create().show();
							return;
						}
							
					}
					MainActivity.getUserAction().joinGroup(group);
				}
			});
			builder.setNegativeButton("Cancel", null);
			builder.create().show();
			return false;
		}
		
	}
	
	class MyOnClickListener implements OnClickListener
	{

		
		String mPath;
		public MyOnClickListener()
		{
			
		}
		public MyOnClickListener(String filePath)
		{
			mPath = filePath;
		}
		
		@Override
		public void onClick(View v) {
			
			if(v.getId() == R.id.send)
				send();
			else if(v.getId() == R.id.group_switcher)
				switchModule();
			else if(R.id.findImage == v.getId())
			{
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				GroupActivity.this.startActivityForResult(intent, 1);
			}
			else if(R.id.msg_ImageS == v.getId())
			{
				if(mPath.contains("/mnt/"))
					mPath = mPath.replace("/mnt/", "/");
				if(!mPath.startsWith("file://"))
					mPath = "file://"+mPath;
				Uri uri = Uri.parse(mPath);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, "image/*");
				GroupActivity.this.startActivity(intent);
			}
				
			
		}
		
	}

	   
	   private class MsgAdapter extends BaseAdapter {

		  ArrayList<MessageData> msg;
		  LayoutInflater inflater;
			public MsgAdapter(ArrayList<MessageData> message) {
				
				inflater = (LayoutInflater) GroupActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				if(message == null)
					message = new ArrayList<MessageData> ();
				msg = message;
			}
			
			public void add(MessageData message)
			{
				msg.add(message);
			}

			@Override
			public int getCount() {
				return msg.size();
			}

			@Override
			public Object getItem(int position) {
				return msg.get(position);
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public View getView(int position, View contentView, ViewGroup parent) {
				
				Hodler hodler ;
				if(contentView == null)
				{
					
					hodler = new Hodler();
					contentView = hodler.layout = inflater.inflate(R.layout.chat_item, null);
					contentView.setTag(hodler);
				}
				else
				{
					hodler = (Hodler)contentView.getTag();
					contentView = hodler.layout;
				}
				
				ImageView icon = (ImageView)hodler.layout.findViewById(R.id.icon);
				icon.setImageResource(R.drawable.icon);
				MessageData message = (MessageData) getItem(position);
				TextView name = (TextView)hodler.layout.findViewById(R.id.name);
				name.setText(message.getDevice().getAddress()+" : ");
				
				TextView msg = (TextView)hodler.layout.findViewById(R.id.msg);
				ImageView msg_image = (ImageView)hodler.layout.findViewById(R.id.msg_ImageS);
		    	
				if(message.isTextType())
				{
					msg_image.setVisibility(View.GONE);
					msg.setVisibility(View.VISIBLE);
					msg.setText((String)message.getMessage());
				}
				else
				{
				
					msg.setVisibility(View.GONE);
					msg_image.setVisibility(View.VISIBLE);
					msg_image.setOnClickListener(new MyOnClickListener(((ImageMessageData)message).getPath()));
					if(message.getMessage()!= null && !((Bitmap)message.getMessage()).isRecycled())
							msg_image.setBackgroundDrawable(new BitmapDrawable((Bitmap)message.getMessage()));
					else
						msg_image.setBackgroundResource(R.drawable.icon);
				
				}
				return contentView;
			}

		}
		
		class Hodler 
		{
			View layout;
		}
	
	
	class GroupAdapter extends BaseAdapter {

		ArrayList<Group> groups;
		
		public GroupAdapter(ArrayList<Group> g)
		{
			if(g !=null)
				groups = g;
			else
				groups = new ArrayList<Group>();
		}

		@Override
		public int getCount() {
			return groups.size();
		}

		@Override
		public Object getItem(int index) {
			return groups.get(index);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			
			Holder holder = null;
			if(convertView == null)
			{
				holder = new Holder();
				holder.layout = (ViewGroup)LayoutInflater.from(GroupActivity.this).inflate(R.layout.group_item, null);
				convertView = holder.layout;
				convertView.setTag(holder);
			}
			else
			{
				holder = (Holder)convertView.getTag();
			}
			
			
			ImageView icon = (ImageView)holder.layout.findViewById(R.id.groupicon);
			TextView name = (TextView)holder.layout.findViewById(R.id.groupName);
			
			name.setText(groups.get(position).getParam().name);
			return convertView;
		}
	}
	
	class Holder
	{
		ViewGroup layout;
	}

	@Override
	public void newMessage(SendTarget target, Object o) {
		initGroupMember((Group)mGroups.getSelectedItem());
	}

	@Override
	public void Join(SendTarget target) {
		initGroup();
		
	}

	@Override
	public void leave(SendTarget target) {
		initGroup();
		
	}

	@Override
	public void newMessage(SendTarget group, SendTarget target, Object o) {
		// TODO Auto-generated method stub
		
	}

	
}
